import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/commonApi.dart';
import 'package:ct_pa_majordomo/utils/date_tools.dart';
import 'package:ct_pa_majordomo/widgets/bottom_sheet/index.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class IdCardPage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isEnterprise;
  final bool isReadOnly;

  const IdCardPage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isEnterprise = false,
    this.isReadOnly = false,
  });

  @override
  State<IdCardPage> createState() => _IdCardPageState();
}

class _IdCardPageState extends State<IdCardPage> {
  final _formKey = GlobalKey<FormState>();
  final _idCardNameController = TextEditingController();
  final _idCardNumberController = TextEditingController();
  bool _isLongTerm = false;
  DateTime? _endDate;
  DateTime? _startDate;
  late ImagePicker _imagePicker;
  File? _frontImageFile;
  File? _backImageFile;

  @override
  void initState() {
    super.initState();
    _imagePicker = ImagePicker();
    if (widget.isEnterprise) {
      _idCardNameController.text = widget.state.company["legalPersonName"] ?? '';
      _idCardNumberController.text = widget.state.company["legalPersonIdCardNo"] ?? '';
      _isLongTerm = widget.state.company["isIdCardLongTerm"] ?? false;
      _endDate = widget.state.company["legalPersonIdCardEndDate"] != null 
        ? DateTime.parse(widget.state.company["legalPersonIdCardEndDate"]) 
        : null;
      _startDate = widget.state.company["legalPersonIdCardStartDate"] != null 
        ? DateTime.parse(widget.state.company["legalPersonIdCardStartDate"]) 
        : null;
    } else {
      _idCardNameController.text = widget.state.person["accountHolder"] ?? '';
      _idCardNumberController.text = widget.state.person["idCardNo"] ?? '';
      _isLongTerm = widget.state.person["isIdCardLongTerm"] ?? false;
      _endDate = widget.state.person["idCardEndDate"] != null 
        ? DateTime.parse(widget.state.person["idCardEndDate"]) 
        : null;
      _startDate = widget.state.person["idCardStartDate"] != null 
        ? DateTime.parse(widget.state.person["idCardStartDate"]) 
        : null;
    }
  }

  @override
  void dispose() {
    _idCardNameController.dispose();
    _idCardNumberController.dispose();
    super.dispose();
  }

  void _showImageSourceOptions(bool isFront) {
    // 使用变量跟踪当前是否有图片选择操作正在进行
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              // 使用FutureBuilder的方式：先关闭弹窗，然后执行拍照
              Future.microtask(() {
                _takePhoto(isFront).then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              // 使用FutureBuilder的方式：先关闭弹窗，然后执行选择图片
              Future.microtask(() {
                _pickImage(isFront).then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  Future<void> _takePhoto(bool isFront) async {
    try {
      var status = await Permission.camera.status;
      if (status.isDenied) {
        await Permission.camera.request();
      } else if (status.isGranted) {
        // 每次创建新的ImagePicker实例，避免状态冲突
        final picker = ImagePicker();
        final pickedImage = await picker.pickImage(
          source: ImageSource.camera,
          imageQuality: 80,
        );
        
        if (pickedImage != null && mounted) {
          setState(() {
            if (isFront) {
              _frontImageFile = File(pickedImage.path);
            } else {
              _backImageFile = File(pickedImage.path);
            }
          });
        }
      }
    } catch (e) {
      print("拍照错误: ${e.toString()}");
      EasyLoading.showError("拍照失败：${e.toString()}");
    }
  }

  Future<void> _pickImage(bool isFront) async {
    try {
      // 每次创建新的ImagePicker实例，避免状态冲突
      final picker = ImagePicker();
      final pickedImage = await picker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );
      
      if (pickedImage != null && mounted) {
        setState(() {
          if (isFront) {
            _frontImageFile = File(pickedImage.path);
          } else {
            _backImageFile = File(pickedImage.path);
          }
        });
      }
    } catch (e) {
      print("选择图片错误: ${e.toString()}");
      EasyLoading.showError("选择图片失败：${e.toString()}");
    }
  }

  Future<void> _uploadImage(File imageFile, bool isFront) async {
    try {
      EasyLoading.show(status: "上传中...");
      
      // 检查文件大小是否超过5M
      final fileSize = await imageFile.length();
      final sizeInMB = fileSize / (1024 * 1024);
      if (sizeInMB > 5) {
        EasyLoading.dismiss();
        EasyLoading.showToast("请上传小于5M的图片");
        return;
      }

      FormData formData = FormData();
      formData.files.add(MapEntry(
        "file",
        await MultipartFile.fromFile(imageFile.path, filename: "id_card_${DateTime.now().millisecondsSinceEpoch}.jpg")
      ));

      Map res = await commonApi.upload(formData);
      EasyLoading.dismiss();

      if (res["code"].toString() != "200") {
        EasyLoading.showError("上传失败：${res["msg"] ?? "未知错误"}");
        return;
      }

      setState(() {
        if (isFront) {
          if (widget.isEnterprise) {
            widget.state.updateCompanyIdCardInfo(
              legalPersonIdCardFrontImg: res["data"]["url"],
            );
          } else {
            widget.state.updatePersonIdCardInfo(
              idCardFrontImg: res["data"]["url"],
            );
          }
        } else {
          if (widget.isEnterprise) {
            widget.state.updateCompanyIdCardInfo(
              legalPersonIdCardBackImg: res["data"]["url"],
            );
          } else {
            widget.state.updatePersonIdCardInfo(
              idCardBackImg: res["data"]["url"],
            );
          }
        }
      });
      EasyLoading.showSuccess("上传成功");
    } catch (e) {
      EasyLoading.dismiss();
      print("上传图片错误: ${e.toString()}");
      EasyLoading.showError("上传失败：${e.toString()}");
    }
  }

  void _selectDate(bool isStart) {
    DateTime selectedDate = isStart ? (_startDate ?? DateTime.now()) : (_endDate ?? DateTime.now());
    
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 300,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('取消'),
                  ),
                  TextButton(
                    onPressed: () {
                      setState(() {
                        if (isStart) {
                          _startDate = selectedDate;
                        } else {
                          _endDate = selectedDate;
                        }
                      });
                      Navigator.pop(context);
                    },
                    child: const Text('确定'),
                  ),
                ],
              ),
              Expanded(
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: selectedDate,
                  minimumDate: DateTime(1900),
                  maximumDate: DateTime(2100),
                  onDateTimeChanged: (DateTime newDate) {
                    selectedDate = newDate;
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  bool _photoValid() {
    if (widget.isEnterprise) {
      if ((widget.state.company["legalPersonIdCardFrontImg"]?.isEmpty ?? true) && _frontImageFile == null) {
        EasyLoading.showError('请上传身份证人像面照片');
        return false;
      }
      if ((widget.state.company["legalPersonIdCardBackImg"]?.isEmpty ?? true) && _backImageFile == null) {
        EasyLoading.showError('请上传身份证国徽面照片');
        return false;
      }
    } else {
      if ((widget.state.person["idCardFrontImg"]?.isEmpty ?? true) && _frontImageFile == null) {
        EasyLoading.showError('请上传身份证人像面照片');
        return false;
      }
      if ((widget.state.person["idCardBackImg"]?.isEmpty ?? true) && _backImageFile == null) {
        EasyLoading.showError('请上传身份证国徽面照片');
        return false;
      }
    }
    return true;
  }

  void _saveForm() async {
    if (!_photoValid()) return;
    if (_formKey.currentState?.validate() ?? false) {
      EasyLoading.show(status: '保存中...');
      
      try {
        // 只上传新选择的图片
        if (_frontImageFile != null) {
          await _uploadImage(_frontImageFile!, true);
        }
        if (_backImageFile != null) {
          await _uploadImage(_backImageFile!, false);
        }
        
        if (widget.isEnterprise) {
          widget.state.updateCompanyIdCardInfo(
            legalPersonIdCardNo: _idCardNumberController.text,
            legalPersonName: _idCardNameController.text,
            legalPersonIdCardStartDate: _startDate?.toIso8601String(),
            legalPersonIdCardEndDate: _isLongTerm ? null : _endDate?.toIso8601String(),
            isIdCardLongTerm: _isLongTerm,
          );
        } else {
          widget.state.updatePersonIdCardInfo(
            idCardNo: _idCardNumberController.text,
            accountHolder: _idCardNameController.text,
            idCardStartDate: _startDate?.toIso8601String(),
            idCardEndDate: _isLongTerm ? null : _endDate?.toIso8601String(),
            isIdCardLongTerm: _isLongTerm,
          );
        }
        
        widget.onStateChanged();
        EasyLoading.dismiss();
        EasyLoading.showSuccess('保存成功');
        Navigator.pop(context);
      } catch (e) {
        EasyLoading.dismiss();
        EasyLoading.showError('保存失败：${e.toString()}');
      }
    }
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageUploadSection(String title, String imageUrl, bool isFront) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Text(
              ' *',
              style: TextStyle(
                color: Colors.red,
                fontSize: 16,
              ),
            ),
          ],
        ),
        const SizedBox(height: 8),
        GestureDetector(
          onTap: widget.isReadOnly ? null : () => _showImageSourceOptions(isFront),
          child: Container(
            width: double.infinity,
            height: 200,
            decoration: BoxDecoration(
              color: ThemeVars.colorBackground,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: ThemeVars.colorBorder),
            ),
            child: imageUrl.isNotEmpty || (isFront ? _frontImageFile != null : _backImageFile != null)
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: imageUrl.isNotEmpty
                        ? Image.network(
                            imageUrl,
                            fit: BoxFit.cover,
                          )
                        : Image.file(
                            File(isFront ? _frontImageFile!.path : _backImageFile!.path),
                            fit: BoxFit.cover,
                          ),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.add_photo_alternate_outlined, size: 50),
                      const SizedBox(height: 8),
                      Text(
                        '点击上传${isFront ? '人像面' : '国徽面'}照片',
                        style: const TextStyle(
                          color: ThemeVars.colorTextSec,
                        ),
                      ),
                    ],
                  ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: widget.isEnterprise ? "法人身份证照片" : "身份证照片",
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            // 只读提示
            if (widget.isReadOnly) _buildReadOnlyTip(),
            _buildImageUploadSection(
              '身份证人像面照片',
              widget.isEnterprise 
                ? widget.state.company["legalPersonIdCardFrontImg"] ?? ''
                : widget.state.person["idCardFrontImg"] ?? '',
              true,
            ),
            const SizedBox(height: 16),
            _buildImageUploadSection(
              '身份证国徽面照片',
              widget.isEnterprise 
                ? widget.state.company["legalPersonIdCardBackImg"] ?? ''
                : widget.state.person["idCardBackImg"] ?? '',
              false,
            ),
            const SizedBox(height: 24),
            TextFormField(
              controller: _idCardNameController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '姓名',
                hintText: '请输入姓名',
                suffixIcon: Icon(Icons.person_outline),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入姓名';
                }
                if (value.length < 2) {
                  return '姓名长度不能小于2个字符';
                }
                if (value.length > 20) {
                  return '姓名长度不能超过20个字符';
                }
                if (!RegExp(r'^[\u4e00-\u9fa5a-zA-Z·]+$').hasMatch(value)) {
                  return '姓名只能包含中文、英文字母和间隔符·';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _idCardNumberController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '身份证号码',
                hintText: '请输入身份证号码',
                suffixIcon: Icon(Icons.credit_card_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入身份证号码';
                }
                if (!RegExp(r'^\d{17}[\dXx]$').hasMatch(value)) {
                  return '请输入正确的身份证号码';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            // Row(
            //   children: [
            //     Checkbox(
            //       value: _isLongTerm,
            //       onChanged: widget.isReadOnly ? null : (value) {
            //         setState(() {
            //           _isLongTerm = value ?? false;
            //           if (_isLongTerm) {
            //             _endDate = null;
            //             _startDate = null;
            //           }
            //         });
            //       },
            //     ),
            //     const Text('长期有效'),
            //   ],
            // ),
            // if (!_isLongTerm) ...[
            //   const SizedBox(height: 16),
            //   ListTile(
            //     title: const Text('有效期开始时间'),
            //     subtitle: Text(_startDate != null
            //         ? DateTools.formatTime(_startDate!.millisecondsSinceEpoch, format: "{y}-{m}-{d}")
            //         : '请选择'),
            //     trailing: const Icon(Icons.arrow_forward_ios, size: 16),
            //     onTap: widget.isReadOnly ? null : () => _selectDate(true),
            //   ),
            //   ListTile(
            //     title: const Text('有效期结束时间'),
            //     subtitle: Text(_endDate != null
            //         ? DateTools.formatTime(_endDate!.millisecondsSinceEpoch, format: "{y}-{m}-{d}")
            //         : '请选择'),
            //     trailing: const Icon(Icons.arrow_forward_ios, size: 16),
            //     onTap: widget.isReadOnly ? null : () => _selectDate(false),
            //   ),
            // ],
            // const SizedBox(height: 24),
            // 只有在非只读模式下才显示保存按钮
            if (!widget.isReadOnly)
              SizedBox(
                width: double.infinity,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeVars.colorPrimary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 